import { getLyric, getSongDetail } from 'api/song.js';

export default class Song {
  constructor({ id, singer, name, album, duration, image, url, canplay, reason }) {
    this.id = id;
    this.singer = singer;
    this.name = name;
    this.album = album;
    this.duration = duration;
    this.image = image;
    this.url = url;
    this.canplay = canplay;
    this.reason = reason;
  }

  getLyric() {
    if (this.lyric) {
      return Promise.resolve(this.lyric);
    } else {
      return new Promise((resolve, reject) => {
        getLyric(this.id).then((res) => {
          this.lyric = res;
          resolve(res);
        });
      });
    }
  }
}

export function createSong(musicData) {
  let canplay = true;
  let reason = '';
  if (musicData.fee === 1 || musicData.privilege?.fee === 1) {
    canplay = false;
    reason = 'VIP Only';
  } else if (musicData.fee === 4 || musicData.privilege?.fee === 4) {
    canplay = false;
    reason = '付费专辑';
  } else if (musicData.noCopyrightRcmd !== null && musicData.noCopyrightRcmd !== undefined) {
    canplay = false;
    reason = '无版权';
  } else if (musicData.privilege?.st < 0) {
    canplay = false;
    reason = '已下架';
  }
  return new Song({
    id: musicData.id,
    singer: filterSinger(musicData.ar),
    name: musicData.name,
    album: musicData.al.name,
    duration: Math.ceil(musicData.dt / 1000),
    image: musicData.al.picUrl,
    url: '',
    canplay,
    reason,
  });
}
export function songAddUrl(song, urls) {
  urls.forEach((urlObj) => {
    if (urlObj.id === song.id) {
      if (urlObj.url && urlObj.freeTrialInfo === null) {
        song.url = urlObj.url;
      } else {
        song.canplay = false;
        song.reason = '暂无播放地址';
      }
    }
  });
}
function filterSinger(singer) {
  let ret = [];
  if (!singer) {
    return '';
  }
  singer.forEach((s) => {
    ret.push(s.name);
  });
  return ret.join('/');
}
